<?php
    session_start();
    //test if a user is logged in
    
    include('conn.php');
    include('verify_user.php');
    require 'anti_csrf.php';

    if (!isset($_POST['CSRFName'])) {
        trigger_error("No CSRFName found, probable invalid request.",E_USER_ERROR);
    }
    $name =$_POST['CSRFName'];
    $token=$_POST['CSRFToken'];
    if (!csrfguard_validate_token($name, $token)) {
        trigger_error("Invalid CSRF token.",E_USER_ERROR);
    }

    
    $shop = $_POST["addItem_shop"];
    
    if(!preg_match('/^[a-zA-Z][\w ]{0,14}$/', $shop)) {
        die('Invalid shop name');
    }
    
    $query = "SELECT * FROM shops WHERE shop_name=$1";
    pg_prepare($con, 'verifyowner', $query) or die('Could not prepare verifyowner');
    $rs = pg_execute($con, 'verifyowner', array($shop)) or die('Could not execute verifyowner');
    $row = pg_fetch_assoc($rs);
    if($row['shop_owner'] != $cur_user) {
        die('You have no right to do so');
    }
    
    $query = "SELECT max(item_id) item_id FROM items";
    $rs = pg_query($con, $query) or die("Could not excute query");
    $row = pg_fetch_assoc($rs);
    $id = $row['item_id'] + 1;
    
    $query = "SELECT max(id) id FROM log";
    $rs = pg_query($con, $query) or die("Could not excute query");
    $row = pg_fetch_assoc($rs);
    $log_id = $row['id'] + 1;
    
    $item_img = $_FILES['addItem_img'];
    $name = $_POST["addItem_itemname"];
    $category = $_POST["addItem_category"];
    $price = "$" . $_POST["addItem_price"];
    $stock = $_POST["addItem_stock"];
    $desc = $_POST["addItem_desc"];
    
    
    //validate user inputs
    include('validate_item_inputs.php');
    
    $allowedExts = array("jpg", "jpeg", "gif", "png");
    $extension = end(explode(".", $_FILES["addItem_img"]["name"]));
    if ((($_FILES["addItem_img"]["type"] == "image/gif") || ($_FILES["addItem_img"]["type"] == "image/jpeg") || ($_FILES["addItem_img"]["type"] == "image/png") || ($_FILES["addItem_img"]["type"] == "image/pjpeg")) && ($_FILES["addItem_img"]["size"]/1024 < 150) && in_array($extension, $allowedExts))
    {
        if ($_FILES["addItem_img"]["error"] > 0) {
            die("Could not upload file");
        } else {
            move_uploaded_file($_FILES["addItem_img"]["tmp_name"], "../img/" . $id . "." . $extension);
        }
    } else {
        die("Invalid file");
    }
    $filename = $id . "." . $extension;
    
    $query = "INSERT INTO items VALUES($1, $2, $3, $4, $5, $6, $7, $8)";
    $log_query = "INSERT INTO log VALUES($1, $2, $3, $4, $5)";
    
    pg_prepare($con, 'prepare1', $query) or die("Could not prepare statement");
    pg_prepare($con, 'logprepare1', $log_query) or die ("Could not prepare log statement");
    
    $res1 = pg_execute($con, 'prepare1', array($id, $name, $category, $desc, $price, $stock, $shop, $filename)) or die("Could not execute query");
    $res2 = pg_execute($con, 'logprepare1', array($cur_user, 'Add Item', $name, date('Y-m-d'), $log_id));
    
    if ($res1 && $res2) {
        pg_query('COMMIT') or die("Could not commit");
    } else {
        pg_query('ROLLBACK') or die("Could not rollback");
    }
    
    pg_close($con);
    header("Location:shop.php?id=" . $cur_user. "&shop=" . $shop);
?>
